<?php 

/**
* 上传类
*/
class Upload
{

	public $config = array(
		'UPLOAD_PATH'=>'./Img/',
		'UPLOAD_NAME'=>'uniqid',
		'UPLOAD_TYPE'=>'.jpg,.png,.gif',
		'UPLOAD_MAX_FILE_SIZE'=>'50000',
		);
	
	// 构造函数传参array()，有传，则选择所传参数，无，则选择默认参数
	function __construct($config=array())
	{
		// $this->config['UPLOAD_PATH'] = isset($config['UPLOAD_PATH']) ? $config['UPLOAD_PATH'] : $this->config['UPLOAD_PATH'];

		foreach ($this->config as $key => $value) {
			$this->config[$key] = isset($config[$key]) ? $config[$key] : $this->config[$key];
		}
		// var_dump($this->config);exit;

	}

	public function save(){


		//读取数组的每一项
		$fileArr = current($_FILES);

		//将数组给_reform方法重组
		$fileList = $this->_reform($fileArr);

		// 检验上传的文件是否合理
		$this->_check($fileList);

		// 将合理文件移动到存储位置
		$this->_move($fileList);

		
		}

		public function _reform($fileArr){
			$fileList = array();

			foreach ($fileArr as $key => $value) {
				foreach ($value as $k => $v) {
					$fileList[$k][$key]=$v;
				}
			}

			return $fileList;
		}

		public function _check($fileList){
			// var_dump($fileList);exit;
			foreach ($fileList as $value) {
				if ($value['size']>$this->config['UPLOAD_MAX_FILE_SIZE']) {
					echo "上传失败，不符合条件";
					exit;
				}
				$suffix = substr($value['name'],strrpos($value['name'], '.'));
				// var_dump($this->config['UPLOAD_TYPE']);exit;
				// strstr()判断某个字符串是否出现，判断上传文件的后缀名是否是默认的格式
				if (!strstr($this->config['UPLOAD_TYPE'],$suffix)) {
					echo "上传失败，上传的后缀为".$suffix.",要求的后缀名为".$this->config['UPLOAD_TYPE'];
					exit;
				}
			}
		}



		public function _move($fileList){
			foreach ($fileList as $key =>  $file) {
			// 获取临时文件和原文件名
			$tmp_name = $file['tmp_name'];
			$name = $file['name'];

			// 判断是否合法上传文件
			if(!is_uploaded_file($tmp_name)) exit;

			//设置上传目录
			$path = $this->config['UPLOAD_PATH'];

			// 判断创建目录
			is_dir($path) || mkdir($path);

			// 组合新名
			$newName = uniqid($key).substr($name,strrpos($name, '.'));

			// 组合新路径
			$newPath = $path.$newName;

			// 移动临时文件
			move_uploaded_file($tmp_name,$newPath);
		}
		return $fileList;

	}





}




 ?>